const app = getApp()
const request = require('../../../utils/request.js');
Page({
  data: {
    order: null,
    paymentMethod: 'wechat' // 默认选择微信支付
  },

  onLoad: function(options) {
    const orderId = options.id
    if (orderId) {
      this.loadOrderDetail(orderId)
    }
  },

  // 加载订单详情
  loadOrderDetail: function(orderId) {
    wx.showLoading({
      title: '加载中...',
    })

    request.request({
      url: `${app.globalData.baseUrl}/api/orders/${orderId}`,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${app.getGlobalToken()}`
      },
      success: (res) => {
        if (res.data.code === 200) {
          this.setData({
            order: res.data.data
          })
        } else {
          wx.showToast({
            title: res.data.message || '加载失败',
            icon: 'none'
          })
        }
      },
      fail: () => {
        wx.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        })
      },
      complete: () => {
        wx.hideLoading()
      }
    })
  },

  // 选择支付方式
  selectPaymentMethod: function(e) {
    const method = e.currentTarget.dataset.method
    this.setData({
      paymentMethod: method
    })
  },

  // 确认支付
  confirmPay: function() {
    const { order, paymentMethod } = this.data
    
    if (!order) {
      wx.showToast({
        title: '订单信息加载失败',
        icon: 'none'
      })
      return
    }

    wx.showLoading({
      title: '处理中...',
    })

    //调用支付接口
    request.request({
      url: `${app.globalData.baseUrl}/api/orders/${order.id}/pay`,
      method: 'POST',
      data: {
        paymentMethod: paymentMethod
      },
      header: {
        'Authorization': `Bearer ${app.getGlobalToken()}`
      },
      success: (res) => {
        if (res.data.code === 200) {
          // 调用微信支付
          if (paymentMethod === 'wechat') {
            wx.showToast({
              title: '支付成功',
              icon: 'success'
            })
            // 支付成功后跳转到订单列表
            app.globalData.needRefresh = true;
            setTimeout(() => {
              wx.navigateTo({
                url: '/pages/orders/orders',
              })
            }, 1500)
          } else {
            // 支付宝支付
            wx.showToast({
              title: '暂不支持支付宝支付',
              icon: 'none'
            })
          }
        } else {
          wx.showToast({
            title: res.data.message || '支付失败',
            icon: 'none'
          })
        }
      },
      fail: () => {
        wx.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        })
      },
      complete: () => {
        wx.hideLoading()
      }
    })
  }
}) 